import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';

/// 这是一个处理加减法的小部件
///
/// [value] 就是要处理的数值
/// [diff] 就是要处理的差值
/// [finalResult] 每次加减后的结果回调一下
/// [size] 加减按钮的框的宽高
/// [scale] 显示数据的框和加减按钮的框的宽比例
class BaseAddAndMinusWidget extends StatefulWidget {
  final int value;
  final int diff;
  final Function(int result) finalResult;
  final double size;
  final double scale;

  const BaseAddAndMinusWidget({Key key, @required this.value, this.diff = 1, @required this.finalResult, this.size = 24, this.scale = 1.5}) : super(key: key);

  @override
  _BaseAddAndMinusWidgetState createState() => _BaseAddAndMinusWidgetState();
}

class _BaseAddAndMinusWidgetState extends State<BaseAddAndMinusWidget> {
  int operateValue = 0;

  @override
  void initState() {
    super.initState();
    operateValue = widget.value;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        buildBox(BaseIconButton(icon: Icons.remove, onPress: () => updateAccNum(-widget.diff)), isLeft: true),
        buildBox(Text(operateValue.toString(), style: TextStyle(color: Color(0xFF333333)))),
        buildBox(BaseIconButton(icon: Icons.add, onPress: () => updateAccNum(widget.diff)), isRight: true),
      ],
    );
  }

  Widget buildBox(Widget child, {bool isLeft = false, bool isRight = false}) {
    return Container(
      width: (!isLeft && !isRight) ? widget.size * widget.scale : widget.size,
      height: widget.size,
      decoration: BoxDecoration(
        borderRadius: (!isLeft && !isRight) ? null : BorderRadius.horizontal(left: Radius.circular(2), right: Radius.circular(2)),
        border: (!isLeft && !isRight) ? Border(top: BorderSide(color: Theme.of(context).scaffoldBackgroundColor, width: 1), bottom: BorderSide(color: Theme.of(context).scaffoldBackgroundColor, width: 1)) : Border.all(width: 1.0, color: Theme.of(context).scaffoldBackgroundColor),
        color: Colors.white,
      ),
      alignment: Alignment.center,
      child: child,
    );
  }

  void updateAccNum(int status) {
    int result = operateValue + status;
    if (result < 0) {
      BaseUtils.showToast("不能为负数");
      return;
    }
    operateValue = result;
    widget.finalResult(operateValue);
    setState(() {});
  }
}
